class Userlink < ActiveRecord::Base
  belongs_to :user

  URL_SIZE = 40
  
  validates_presence_of :user_id
  validates_presence_of :url
  
  # This validation currently doesn't work, so we have to 
  # do a manual one, but this will soon be fixed in a future version of Rails
  validates_associated :user

  validates_format_of :url,
                      :with => /^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix,
                      :message => "must be a valid URL".t

  def self.url_exists?(url)
    begin
      uri = URI.parse(url) 
      http_connection = Net::HTTP.new(uri.host, uri.port)  
      response, data = http_connection.head("/" , nil)  
      response.code == "200"
    rescue
      return false
    end
  end  

  def self.exists?(user_id_to_test, url_to_test)
    self.find_by_user_id_and_url(user_id_to_test, url_to_test) ? true : false
  end
  
  protected
    def validate
      errors.add(:user_id, "is invalid".t) unless User.find_by_id(user_id)
      errors.add(:url, "cannot be reached".t) unless Userlink.url_exists?(url)
    end
    
    def validate_on_create
      errors.add_to_base("Already exists".t) if Userlink.exists?(user_id, url)
    end  
end
